﻿using System;
using System.Collections.Generic;
using System.Web.Security;

using mvcForum.Web.Interfaces;
using mvcForum.Web.Providers;
using mvcForum.Core;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Services {

	public class UserService : IUserService {
		private readonly IContext context;

		public UserService(IContext context) {
			this.context = context;
		}

		public IEnumerable<ForumUser> GetOnlineUsers() {
			// Well, we can't run without this provider, but we're still making sure!
			if (Membership.Provider is mvcForum.Web.Providers.MembershipProviderWrapper) {
				MembershipProviderWrapper provider = (MembershipProviderWrapper)Membership.Provider;
				if (provider.ActualProvider is SimpleMembershipProvider) {
					TimeSpan timeSpan = TimeSpan.FromMinutes(((SimpleMembershipProvider)provider.ActualProvider).UserIsOnlineTimeWindow);
					DateTime last15Mins = DateTime.UtcNow.Subtract(timeSpan);
					return this.context.GetRepository<ForumUser>().ReadMany(u => u.LastVisit > last15Mins);
				}
			}
			return new List<ForumUser>();
		}
	}
}